/**
 * 公共JavaScript函数
 * 功能反馈:15058593138@qq.com
 */

// AJAX请求函数
function ajaxRequest(url, data, callback, method = 'POST') {
    const xhr = new XMLHttpRequest();
    let formData = null;
    
    if (method.toUpperCase() === 'GET' && data) {
        const params = [];
        for (let key in data) {
            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        }
        url += (url.indexOf('?') === -1 ? '?' : '&') + params.join('&');
        data = null;
    } else if (data) {
        formData = new FormData();
        for (let key in data) {
            formData.append(key, data[key]);
        }
    }
    
    xhr.open(method, url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                let result;
                try {
                    result = JSON.parse(xhr.responseText);
                } catch (e) {
                    result = {
                        code: 1,
                        msg: '解析服务器响应失败'
                    };
                }
                callback(result);
            } else {
                callback({
                    code: 1,
                    msg: '网络请求失败：' + xhr.status
                });
            }
        }
    };
    xhr.send(formData);
}

// 获取表单数据
function getFormData(formId) {
    const form = document.getElementById(formId);
    if (!form) return {};
    
    const data = {};
    const elements = form.elements;
    
    for (let i = 0; i < elements.length; i++) {
        const element = elements[i];
        if (!element.name) continue;
        
        if (element.type === 'checkbox' || element.type === 'radio') {
            if (element.checked) {
                data[element.name] = element.value;
            }
        } else if (element.type !== 'button' && element.type !== 'submit' && element.type !== 'reset') {
            data[element.name] = element.value;
        }
    }
    
    return data;
}

// 提交表单
function submitForm(formId, url, callback) {
    const data = getFormData(formId);
    ajaxRequest(url, data, callback);
}

// 显示遮罩层
function showMask(content, title = '提示', buttons = []) {
    // 创建遮罩层
    const mask = document.createElement('div');
    mask.className = 'mask';
    
    // 创建内容容器
    const container = document.createElement('div');
    container.className = 'mask-container';
    
    // 创建标题
    const titleDiv = document.createElement('div');
    titleDiv.className = 'mask-title';
    titleDiv.innerHTML = title + '<span class="mask-close" onclick="closeMask()">×</span>';
    
    // 创建内容
    const contentDiv = document.createElement('div');
    contentDiv.className = 'mask-content';
    contentDiv.innerHTML = content;
    
    // 创建按钮区域
    const buttonDiv = document.createElement('div');
    buttonDiv.className = 'mask-buttons';
    
    // 添加按钮
    buttons.forEach(function(btn) {
        const button = document.createElement('button');
        button.className = 'mask-button ' + (btn.class || '');
        button.innerHTML = btn.text;
        button.onclick = function() {
            if (btn.click) {
                btn.click();
            } else {
                closeMask();
            }
        };
        buttonDiv.appendChild(button);
    });
    
    // 如果没有按钮，添加默认的关闭按钮
    if (buttons.length === 0) {
        const closeButton = document.createElement('button');
        closeButton.className = 'mask-button';
        closeButton.innerHTML = '关闭';
        closeButton.onclick = closeMask;
        buttonDiv.appendChild(closeButton);
    }
    
    // 组装遮罩层
    container.appendChild(titleDiv);
    container.appendChild(contentDiv);
    container.appendChild(buttonDiv);
    mask.appendChild(container);
    
    // 添加到页面
    document.body.appendChild(mask);
    
    // 记录当前遮罩层
    window.currentMask = mask;
}

// 关闭遮罩层
function closeMask() {
    if (window.currentMask) {
        document.body.removeChild(window.currentMask);
        window.currentMask = null;
    }
}

// 显示Toast提示
function showToast(message, type = 'info', duration = 3000) {
    // 创建Toast元素
    const toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    toast.innerHTML = message;
    
    // 添加到页面
    document.body.appendChild(toast);
    
    // 设置动画
    setTimeout(function() {
        toast.classList.add('toast-show');
    }, 10);
    
    // 自动关闭
    setTimeout(function() {
        toast.classList.remove('toast-show');
        setTimeout(function() {
            document.body.removeChild(toast);
        }, 500);
    }, duration);
}

// 确认对话框
function confirmDialog(message, callback) {
    showMask(message, '确认', [
        {
            text: '取消',
            class: 'mask-button-default',
            click: closeMask
        },
        {
            text: '确定',
            class: 'mask-button-primary',
            click: function() {
                closeMask();
                callback();
            }
        }
    ]);
}

// 加载页面
function loadPage(page) {
    // 获取当前参数
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.set('page', page);
    
    // 刷新页面
    window.location.search = urlParams.toString();
}

// 修改状态
function changeStatus(id, status, callback) {
    if (!id) return;
    
    confirmDialog('确定要' + (status == 1 ? '启用' : '禁用') + '此记录吗？', function() {
        ajaxRequest(window.location.href, {
            act: 'status',
            id: id,
            status: status
        }, function(res) {
            if (res.code === 0) {
                showToast(res.msg, 'success');
                if (callback) callback();
            } else {
                showToast(res.msg, 'error');
            }
        });
    });
}

// 删除记录
function deleteRecord(id, callback) {
    if (!id) return;
    
    confirmDialog('确定要删除此记录吗？删除后不可恢复！', function() {
        ajaxRequest(window.location.href, {
            act: 'delete',
            id: id
        }, function(res) {
            if (res.code === 0) {
                showToast(res.msg, 'success');
                if (callback) callback();
            } else {
                showToast(res.msg, 'error');
            }
        });
    });
}

// 批量删除
function batchDelete(idField) {
    const selectedIds = [];
    const checkboxes = document.querySelectorAll('input[name="' + idField + '"]:checked');
    
    if (checkboxes.length === 0) {
        showToast('请选择要删除的记录', 'warning');
        return;
    }
    
    checkboxes.forEach(function(checkbox) {
        selectedIds.push(checkbox.value);
    });
    
    confirmDialog('确定要删除所选的 ' + selectedIds.length + ' 条记录吗？删除后不可恢复！', function() {
        ajaxRequest(window.location.href, {
            act: 'batch_delete',
            ids: selectedIds.join(',')
        }, function(res) {
            if (res.code === 0) {
                showToast(res.msg, 'success');
                window.location.reload();
            } else {
                showToast(res.msg, 'error');
            }
        });
    });
}

// 选择全部
function selectAll(selector, target) {
    const checkAll = document.querySelector(selector);
    const checkboxes = document.querySelectorAll(target);
    
    checkboxes.forEach(function(checkbox) {
        checkbox.checked = checkAll.checked;
    });
}

// 表单验证
function validateForm(formId) {
    const form = document.getElementById(formId);
    if (!form) return true;
    
    const elements = form.elements;
    
    for (let i = 0; i < elements.length; i++) {
        const element = elements[i];
        
        // 检查required属性
        if (element.hasAttribute('required') && !element.value.trim()) {
            const fieldName = element.getAttribute('data-name') || element.name;
            showToast(fieldName + ' 不能为空', 'warning');
            element.focus();
            return false;
        }
        
        // 检查pattern属性
        if (element.hasAttribute('pattern') && element.value.trim()) {
            const pattern = new RegExp(element.getAttribute('pattern'));
            if (!pattern.test(element.value.trim())) {
                const fieldName = element.getAttribute('data-name') || element.name;
                showToast(fieldName + ' 格式不正确', 'warning');
                element.focus();
                return false;
            }
        }
    }
    
    return true;
}
